<?php
header("Content-Type: text/html; charset=iso-8859-1");
require 'include.php';
$equipe = (!empty($_REQUEST['equipe'])) ? $_REQUEST['equipe'] : "";
$match = (!empty($_REQUEST['match'])) ? $_REQUEST['match'] : "";
if(isset($_REQUEST['prochain_presences'])){
	if(isset($_SESSION['prochain_presences'])){
		unset($_SESSION['prochain_presences']);		
		echo 0;
	} 
	else {
		$_SESSION['prochain_presences'] = 1;	
		echo 1;
	}
	if(isset($_SESSION['presences'])) unset($_SESSION['presences']);
}
elseif($equipe){
	$team = new equipe($equipe);
	$team->print_presences();
}
elseif($match){
	if(!$equipe) $equipe = (!empty($_SESSION['presences_equipe'])) ? $_SESSION['presences_equipe'] : "";
	$membre = (!empty($_REQUEST['membre'])) ? $_REQUEST['membre'] : "";
	$annee = (date('m')>7) ? date('Y') : date('Y')-1;
	$ok_membre = 1;
	$q = "select licence from comptabilite where membre_id = '$membre'";
	$r = ExecRequete($q);
	if($s = LigneSuivante($r)){
		$ok_valide = ($s->licence) ? 1 : 0;
	}
	else $ok_valide = 0;
	$delete = 0;
	$q = "select id from membre_matchs where membre_id = '$membre' and no_match = '$match'";
	$r = ExecRequete($q);
	if(mysql_num_rows($r)){
		$q = "delete from membre_matchs where membre_id = '$membre' and no_match = '$match'";
		ExecRequete($q);
		if($ok_valide) $echo = -1;
		else $echo = 0;
		$delete = 1;
	}
	else{
		$q = "insert into membre_matchs (membre_id,no_match) values('$membre','$match')";
		ExecRequete($q);
		if($ok_valide) $echo = 1;
		else $echo = 0;
	}
	$tab = (!empty($_SESSION['presences'])) ? $_SESSION['presences'] : array();
	if(count($tab)){
		$membre = new membre($membre);
		$nom = $membre->prenom." ".(substr($membre->nom,0,1)).".";
		$matchs = array();
		for($j = 1; $j < count($tab); $j++){
			$row = $tab[$j];
			if(strpos($row[0], $nom) !== FALSE){
				for($i = 1; $i < count($row); $i++){
					if(strpos($row[$i],'update_presence('.$membre->id.',"'.$match.'","'.$equipe.'")') !== FALSE){
						if(!$delete) $tab[$j][$i] = str_replace("type = 'checkbox'","type = 'checkbox' checked = 'checked'",$tab[$j][$i]);
						else $tab[$j][$i] = str_replace("checked = 'checked'","",$tab[$j][$i]);
						if($ok_valide){
							$tab[$j][$i] = str_replace('vert','roug', $tab[$j][$i]);
							$tab[$j][$i] = str_replace('rouge','vert',$tab[$j][$i]);
							$tab[$j][$i] = str_replace('roug','rouge',$tab[$j][$i]);														
						}
						if(ereg("(.*value\ =\ \')([0-9]+)(.*)([0-9]+)",$tab[count($tab)-1][$i],$regs)){
							$tab[count($tab)-1][$i] = $regs[1].($regs[2]+$echo).$regs[3].($regs[4]+$echo);
							$tab[count($tab)-1][$i] = str_replace('vert','roug',$tab[count($tab)-1][$i]);
							$tab[count($tab)-1][$i] = str_replace('rouge','vert',$tab[count($tab)-1][$i]);
							$tab[count($tab)-1][$i] = str_replace('roug','rouge',$tab[count($tab)-1][$i]);							
						}
					}
				}
			}
		}
		$_SESSION['presences'] = $tab;
	}
	echo $echo;
}
?>